﻿using System;
using System.IO;
using Net.Event;
using Net.Helper;
using Net.Share;
using Net.System;
using Newtonsoft_X.Json;
using WebSocketSharp;

namespace Net.Server
{
    /// <summary>
    /// web客户端对象
    /// </summary>
    public class WebPlayer : ClientPeerBase
    {
        /// <summary>
        /// webSocket套接字
        /// </summary>
        public WebSocket WSClient { get; set; }

        public override void ReceiveHandler()
        {
            while (ReceiveList.TryDequeue(out var segment))
            {
                ReceiveHandler(ref segment);
                BufferPool.Push(segment);
            }
        }

        protected override void SendByteData(ISegment buffer)
        {
            if (buffer.Count == Frame)//解决长度==6的问题(没有数据)
                return;
            trafficStatistics.SentPacketsPerSecond++;
            trafficStatistics.SentBytesPerSecond += buffer.Count;
            WSClient.Send(new MemoryStream(buffer.Buffer, buffer.Offset, buffer.Count, true, true), buffer.Count);
        }

        internal void ReceiveHandler(string text)
        {
            try
            {
                var message = JsonConvert.DeserializeObject<MessageModel>(text);
                var model = RpcUnitFactory.Create(cmd: message.cmd, kernel: true, protocol: message.func.CRCU32(), pars: message.GetPars());
                OnCommand1Handler(model, null);
            }
            catch (Exception ex)
            {
                NDebug.LogError($"[{this}]json解析出错:" + ex);
                var model = new MessageModel(0, "error", new object[] { ex.Message });
                var jsonStr = JsonConvert.SerializeObject(model);
                WSClient.Send(jsonStr);
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            WSClient?.Close();
        }
    }
}
